package wangjg.coco.common;

import java.io.File;
import java.io.IOException;

public class FileExplorer {
	private boolean useCmd;
	private String cmd;

	public FileExplorer() {
	}

	public FileExplorer(boolean useCmd, String cmd) {
		this.useCmd = useCmd;
		this.cmd = cmd;
	}

	public void open(File file){
		if(!file.isAbsolute()){
			return;
		}
		if(file.isDirectory()){
			this.openDefault(file);
			return;
		}
		if(!this.useCmd){
			this.openDefault(file.getParentFile());
		}else{
			this.openWinExplorer(file);
		}
	}
	
	private boolean isWindows(){
		String os = System.getProperty("os.name");
		if(os!=null && os.indexOf("Windows")!=-1){
			return true;
		}
		return false;
	}
	
	private void openDefault(File file){
		try {
			java.awt.Desktop.getDesktop().open(file);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	private void openWinExplorer(File file){
		String cmd;
		if(this.isWindows()){
			String path = file.getPath();
			path = path.replaceAll("\\\\", "\\\\\\\\");
			cmd = this.cmd.replaceAll("\\{0\\}", path);
		}else{
			String path = file.getPath();
			cmd = this.cmd.replaceAll("\\$1", path);
		}
		try {
			Runtime.getRuntime().exec(cmd);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
